<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 警告条添加商品 -->
      <el-alert title="添加商品信息" center :closable="false" type="info" show-icon></el-alert>
      <!-- 步骤条 -->
      <el-steps :space="200" align-center :active="activeIndex-0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <el-form
        :model="addForm"
        label-position="top"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
      >
        <!-- tab栏 -->
        <el-tabs
          v-model="activeIndex"
          @tab-click="tabClick"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in canList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="item" v-for="(item,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              class="upload-demo"
              :action="this.baseURL+'upload'"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button type="primary" @click="add" class="addbtn">添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- dialog -->
    <el-dialog
      title="图片预览"
      :visible.sync="previewVisible"
      width="50%">
      <!-- <img :src="previePath" class="previewImg"> -->
      <el-image :src="previePath" class="previewImg"></el-image>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  
  data() {
    return {
      activeIndex: '0',
      // 添加商品的表单
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品分类
        goods_cat: [],
        // 图片零时存放路径
        pics:[],
        // 商品简介
        goods_introduce:''
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          { required: true, message: '输入商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '输入商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '输入商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '输入商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      cateList: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 参数列表
      canList: [],
      // 静态属性
      onlyTableData: [],
      // 手动为upload设置请求头，因为upload用的不是axios发送的请求
      headerObj:{
        Authorization : window.sessionStorage.getItem('token')
      },
      // 预览图片的路径
      previePath:'',
      previewVisible:false
    }
  },
  methods: {
    // 商品分类列表的数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('商品列表数据获取失败')
      }
      this.cateList = res.data
      // console.log(this.cateList)
      // console.log(this.baseURL)
    },
    // 监听分类
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      // console.log(this.addForm.goods_cat);
    },
    // 标签页离开
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        console.log('原来的' + oldActiveName + '前往的' + activeName)
        return false
      }
    },
    // 点击tab触发
    async tabClick() {
      if (this.activeIndex === '1') {
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('参数列表数据获取失败')
        }
        res.data.forEach(element => {
          element.attr_vals =
            element.attr_vals.length == 0 ? [] : element.attr_vals.split(' ')
        })

        this.canList = res.data
        console.log(this.canList)
      } else if (this.activeIndex === '2') {
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('参数列表数据获取失败')
        }
        this.onlyTableData = res.data
        console.log(this.onlyTableData)
      }
    },
    // handlePreview,处理图片预览
    handlePreview(file){
      this.previePath = file.response.data.url
      this.previewVisible = true
      
    },
    // 处理图片上传成功的函数
    handleSuccess(response){
      // console.log(response);
      var picObj = {
        pic:response.data.tmp_path
      }
      this.addForm.pics.push(picObj)
      console.log(this.addForm);
      
    },
    // 处理移除图片
    handleRemove(file){
      const filePath = file.response.data.tmp_path
      const i = this.addForm.pics.findIndex(item => item.pic == filePath)
      this.addForm.pics.splice(i,1)
      console.log(this.addForm.pics);
      
    },
    add(){
      this.$refs.addFormRef.validate(valid => {
        if(!valid){
          this.$message.error('请填写带*号的文本框')
        }
        // 将级联选择框的数组变成字符串，但是不能再数据绑定的对象上操作
        // 利用lodash的cloneDeep进行深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // this.many
        
        console.log(this.addForm.goods_cat);
        
      })
    }

  },
  created() {
    this.getCateList()
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="less" scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg{
  width: 100%;
}
.addbtn{
  margin-top: 15px;
}
</style>